package cn.syy.template;

import cn.hutool.core.lang.Assert;
import cn.syy.properties.CosProperties;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.auditing.ImageAuditingRequest;
import com.qcloud.cos.model.ciModel.auditing.ImageAuditingResponse;

import java.io.File;
import java.io.InputStream;

public class CosTemplate {

    private CosProperties cosProperties;
    private COSClient cosClient;

    public CosTemplate (CosProperties cosProperties,COSClient cosClient){
        this.cosProperties = cosProperties;
        this.cosClient = cosClient;
    }

    public String uploadFile(InputStream inputStream,String floder,String fileName){
        // 指定文件将要存放的存储桶
        String bucketName = cosProperties.getBucketName();
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        String key = floder + "/" +fileName;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream,new ObjectMetadata());
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        System.out.println(putObjectResult);
        // 判断上传是否成功
        String eTag = putObjectResult.getETag();
        if (eTag == null || eTag == "null"){
            throw  new RuntimeException("图片审核失败");
        }
        // 调用图片审核的方法，判断图片审核是否成功
        Boolean aBoolean = this.imageAuditing(bucketName, key);
        Assert.isTrue(aBoolean,"图片审核失败");
       //  https://0403java-1318645800.cos.ap-chengdu.myqcloud.com/gallop/1722931842491.jpg
        String filePath = String.format(cosProperties.getImagePathTemplate(), bucketName, cosProperties.getRegion(), floder, fileName);
        return filePath;
    }

    /**
     * 图片审核
     * @param bucketName
     * @param objKey
     * @param cosClient
     * @return
     */
    public Boolean imageAuditing(String bucketName,String objKey){
        //1.创建任务请求对象
        ImageAuditingRequest request = new ImageAuditingRequest();
        //2.添加请求参数 参数详情请见 API 接口文档
        //2.1设置请求 bucket
        request.setBucketName(bucketName);
        //2.2设置审核策略 不传则为默认策略（预设）
        request.setDetectType(cosProperties.getDetectType());
        //2.3设置 bucket 中的图片位置
        request.setObjectKey(objKey);
        //3.调用接口,获取任务响应对象
        ImageAuditingResponse response = cosClient.imageAuditing(request);
        System.out.println(response);
        return  response.getResult().equals("0");
    }
}
